package com.question.common.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.question.business.auth.model.dto.UserDetailDTO;
import com.question.business.role.service.IRoleMenuService;
import com.question.common.constants.SecurityConstants;
import com.question.common.constants.StringConstants;
import com.question.common.utils.CurrentUserUtil;
import com.question.common.utils.IdUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author star
 * @version 1.0.0
 * @Description: 认证拦截
 * @since 2020/7/20
 */
@Slf4j
@Component
@AllArgsConstructor
public class AuthTokenFilter extends OncePerRequestFilter {

    private final CurrentUserUtil currentUserUtil;

    private final IRoleMenuService roleMenuService;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        // 处理日志ID
        handleTraceId(request);
        // 获取token
        String token = currentUserUtil.getToken(request);

        // 验证token
        if (StringUtils.isNotBlank(token)) {
            UserDetailDTO userDetail = currentUserUtil.getUser(token);
            handleInterfaceAuth(request, userDetail);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            currentUserUtil.setUser(token, userDetail);
            logger.info(String.format("Authenticated userDetail %s, setting security context", userDetail.getUsername()));
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 处理接口授权
     *
     * @param request    请求信息
     * @param userDetail 用户信息
     * @throws MalformedURLException
     */
    private void handleInterfaceAuth(@NotNull HttpServletRequest request, UserDetailDTO userDetail) throws MalformedURLException {
        if (SecurityConstants.SUPER_ADMIN.equals(userDetail.getUsername())) {
            return;
        }
        URL url = new URL(request.getRequestURL().toString());
        String interfaceAddress = url.getPath();
        if (SecurityConstants.NOT_INTERFACE_AUTH.contains(interfaceAddress)) {
            return;
        }
        boolean isMenuAuth = roleMenuService.isInterfaceAuth(userDetail.getRoles(), interfaceAddress);
        if (!isMenuAuth) {
            throw new AccessDeniedException("接口未授权");
        }
    }

    /**
     * 处理日志ID
     *
     * @param request 请求
     */
    private void handleTraceId(@NotNull HttpServletRequest request) {
        String traceId = request.getHeader(StringConstants.TRACE_ID_HEADER);
        if (StringUtils.isBlank(traceId)) {
            traceId = IdUtil.generateId();
        }
        MDC.put(StringConstants.TRACE_ID, traceId);
    }

}
